<template>
  <view class="upload-container">
    <!-- 已上传的图片列表 -->
    
    <block v-if="value && value.length > 0">
      <view 
        v-for="(item, index) in value" 
        :key="index" 
        class="image-item"
      >
        <image 
          :src="item" 
          class="uploaded-image" 
          mode="aspectFill"
          @click="previewImage(index)"
        />
        <view class="delete-btn" @click="deleteImage(index)">
          <u-icon name="close" color="#fff" size="12"></u-icon>
        </view>
      </view>
    </block>
    
    <!-- 上传按钮 -->
    <block v-if="value.length < maxCount">
      <view class="upload-btn" @click="handleUpload">
        <view class="upload-icon">
          <u-icon name="camera" color="#BBC1D0" size="20px"></u-icon>
        </view>
      </view>
    </block>
  </view>
</template>

<script>
import { updownImage } from '@/util/update';

export default {
  name: 'Upload',
  props: {
    // 文件列表
    value: {
      type: Array,
      default: () => []
    },
    // 最大上传数量
    maxCount: {
      type: Number,
      default: 5
    },
    // 图片尺寸
    imageSize: {
      type: String,
      default: '152rpx'
    }
  },
  
  methods: {
    /**
     * 处理上传
     */
    handleUpload() {
      console.log("handleUpload")
      updownImage().then(res => {
        console.log("res",res)
        if (res && res.length > 0) {
          let values=this.value
          res.forEach(item => {
            values.push(item)
          })
         
          this.$emit('input', values);
        }
      }).catch(err => {
        console.error('上传失败:', err);
        this.$u.toast('上传失败，请重试');
      });
    },
    
    /**
     * 删除图片
     */
    deleteImage(index) {
      console.log("index",index)
      const newFileList = [...this.value];
      newFileList.splice(index, 1);
      this.$emit('input', newFileList);
      this.$emit('delete', { index, file: this.value[index] });
    },
    
    /**
     * 预览图片
     */
    previewImage(index) {
      uni.previewImage({
        current: index,
        urls: this.value
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.upload-container {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
}

.image-item {
  position: relative;
  margin-right: 10rpx;
  margin-bottom: 10rpx;
}

.uploaded-image {
  width: 152rpx;
  height: 152rpx;
  border-radius: 10rpx;
}

.delete-btn {
  position: absolute;
  top: -8rpx;
  right: -8rpx;
  width: 32rpx;
  height: 32rpx;
  background: rgba(0, 0, 0, 0.6);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.upload-btn {
  width: 152rpx;
  height: 152rpx;
  border-radius: 10rpx;
  border: 1rpx solid #ECECF1;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 10rpx;
}

.upload-icon {
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
